package cn.lingyangwl.agile.gateway.sign.core;

import cn.lingyangwl.agile.gateway.model.*;
import cn.lingyangwl.agile.gateway.sign.model.*;
import cn.lingyangwl.framework.core.response.format.*;
import cn.lingyangwl.framework.sign.*;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 支付接口的签名
 * @author shenguangyang
 */
@Slf4j
@Component
public class RqRsApiSign extends AbstractApiSign {

    @Override
    public SignModeEnum getMode() {
        return SignModeEnum.RQ_RS;
    }

    @Override
    public boolean isGenRespSign(SignContext context) {
        SignPayload signPayload = context.getSignPayload();
        return Objects.nonNull(signPayload);
    }

    @Override
    public void genRespSign(SignContext context, JSONObject serviceResp) {
        try {
            Object data = serviceResp.get(ResponseFormatHandler.getFormat().getDataName());
            SignPayload signPayload = context.getSignPayload();
            if (Objects.isNull(signPayload)) {
                return;
            }
            AccessKeyResp accessKeyResp = context.getAccessKeyResp();
            String secretId = accessKeyResp.getSecretId();
            String secretKey = accessKeyResp.getSecretKey();
            SignType signType = SignType.ofByType(signPayload.getSignType());

            SignPayload respSignPayload = SignUtils.genSign(signType, secretId, secretKey, data);

            HttpHeaders headers = context.getGatewayContext().getExchange().getResponse().getHeaders();
            respSignPayload.toMapOfStringType().forEach(headers::add);
        } catch (Exception e) {
            log.error("签名生成失败, ", e);
            throw new SignException("签名生成失败");
        }
    }
}
